package com.dibang.app.view;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import com.dibang.app.R;

import org.xml.sax.XMLReader;

import java.util.HashMap;

/**
 * Created by wxl on 2019/8/11.
 */
public class GroupNumberHtmlHandler implements Html.TagHandler {

    public static final String GROUP_NUM_TAG = "number";

    private Context context;

    public  int mStart ;

    private HashMap<String, Integer> mMaps = new HashMap<>();

    public GroupNumberHtmlHandler(Context context) {
        this.context = context;
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        if (!tag.equals(GROUP_NUM_TAG)) {
            return;
        }

        if (opening) {
            mStart = output.length();
            if (tag.equals(GROUP_NUM_TAG)) {
                mMaps.put(GROUP_NUM_TAG, mStart);
            }
        } else {
            int mEnd = output.length();
            if (tag.equals(GROUP_NUM_TAG)) {
                output.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, android.R.color.holo_red_dark)),
                        mMaps.get(GROUP_NUM_TAG), mEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }


    public static void setText(TextView textView, String currentNum,String totalNum){
        String content = String.format("<html>拼团人数:<%s>%s</%s>/"+totalNum+"</html>",
                GROUP_NUM_TAG,currentNum,GROUP_NUM_TAG);
        textView.setText(Html.fromHtml(content, null, new GroupNumberHtmlHandler(textView.getContext())));
        textView.setMovementMethod(LinkMovementMethod.getInstance());//响应点击事件
    }
}
